package com.yaozheng.vocationaltraining.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.HomeNewsImageAdapter;
import com.yaozheng.vocationaltraining.iview.IHomeView;
import com.yaozheng.vocationaltraining.service.HomeService;
import com.yaozheng.vocationaltraining.service.impl.cache.HomeCacheServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.LogUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.widget.HomeLearnTextProgressView;

/**
 * 首页
 *
 * @author Administrator
 */
@EFragment(R.layout.fragment_home)
public class HomeFragment extends BaseFragment implements IHomeView {
    @ViewById
    ViewPager viewPager;
    /**
     * viewPagerStatus 状态
     */
    LinearLayout viewPagerStatusViewGroup;

    List<ImageView> viewPagerStatusImageViews;
    @ViewById
    ImageView viewPagerStatusImageView1, viewPagerStatusImageView2,
            viewPagerStatusImageView3, viewPagerStatusImageView4, userAvatarImage;
    @ViewById
    TextView homeNameText, homeExplanation, homeGradeTextView, homeFeatsTextView, homeLearningProgressText, homeExperienceTextView, homeRankingTextView, homePosition;
    @ViewById
    ImageView medalBrandImage, medalGoodsImage, medalImage, medalRepairImage, medalSalesImage, medalServiceImage;
    @ViewById
    HomeLearnTextProgressView homeLearningProgressView;
    @Bean(HomeCacheServiceImpl.class)
    HomeService homeService;

    HomeNewsImageAdapter homeNewsImageAdapter;

    JSONObject currUserJsonObject;

    BitmapLoader userBitmapLoader;


    int currSelect;

    boolean isAutomaticScroll;

    Thread automaticScroll;


    @AfterViews
    public void initView() {
        userBitmapLoader = new BitmapLoader(Glide.with(this), R.drawable.user_img);
        homeService.init(this);
        homeNewsImageAdapter = new HomeNewsImageAdapter(getChildFragmentManager());
        viewPager
                .setAdapter(homeNewsImageAdapter);
        viewPagerStatusImageView4.setVisibility(View.GONE);
        viewPagerStatusImageViews = new ArrayList<ImageView>();
        viewPagerStatusImageViews.add(viewPagerStatusImageView1);
        viewPagerStatusImageViews.add(viewPagerStatusImageView2);
        viewPagerStatusImageViews.add(viewPagerStatusImageView3);
        isAutomaticScroll = true;
//        viewPagerStatusImageViews[3] = viewPagerStatusImageView4;
        viewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        currSelect = position;
                        HomeFragment.this.onPageSelected(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        switch (state) {
                            case ViewPager.SCROLL_STATE_SETTLING:
                                isAutomaticScroll = true;
                                break;
                            case ViewPager.SCROLL_STATE_DRAGGING:
                                isAutomaticScroll = false;
                                break;
                        }

                    }

                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }
                });
        showSignActivity();
        onPageSelected(0);
        loadData();
        automaticScroll();
    }

    public void loadData() {
        homeService.loadHomeData();
    }

    /**
     * 自动滚动
     */
    public void automaticScroll() {
        if (automaticScroll == null) {
            automaticScroll = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isResponseResult()) {
                        try {
                            Thread.sleep(1000 * 6);
                            automaticScrollUpdateUI();
                        } catch (InterruptedException e) {
                            ErrorUtils.outErrorLog(e);
                        }
                    }
                }
            });
            automaticScroll.start();

        }
    }

    @UiThread
    public void automaticScrollUpdateUI() {
        if (isResponseResult()) {
            if (isAutomaticScroll) {
                if (viewPagerStatusImageViews.size() - 1 <= currSelect) {
                    currSelect = 0;
                } else {
                    currSelect++;
                }
                viewPager.setCurrentItem(currSelect, true);
            }
//            automaticScroll();
        }
    }

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getBaseActivity();
    }

    /**
     * 显示签到对话框
     */
    public void showSignActivity() {
        Calendar date = Calendar.getInstance();
        int year = date.get(Calendar.YEAR);
        int month = date.get(Calendar.MONTH) + 1;
        int day = date.get(Calendar.DAY_OF_MONTH);
        String dateStr = year + "" + (month < 10 ? "0" + month : month) + ""
                + (day < 10 ? "0" + day : day);
        SharedPreferences sharedPreferences = getBaseActivity()
                .getSharedPreferences();
        String lastSignDate = sharedPreferences.getString("lastSignDate", "");
        if (!dateStr.equals(lastSignDate)) {
            Editor editor = sharedPreferences.edit();
            editor.putString("lastSignDate", dateStr);
            editor.commit();
            Intent intent = new Intent();
            intent.setClassName(getContext(), Constants.HOME_SIGN_TASK_ACTIVITY_CLASS_NAME);
            startActivity(intent);
        }
    }


    /**
     * 设置选中状态
     *
     * @param position
     */
    public void onPageSelected(int position) {
        if (viewPagerStatusImageViews == null)
            return;
        for (int i = 0; i < viewPagerStatusImageViews.size(); i++) {
            if (position != i) {
                viewPagerStatusImageViews.get(i).setEnabled(true);
            } else {
                viewPagerStatusImageViews.get(i).setEnabled(false);
            }
        }
    }

    /**
     * 学习进度
     */
    @Click(R.id.learnProgressLayout)
    public void learnProgressLayoutClick() {
        Intent intent = new Intent();
        intent.setClassName(getActivity(),
                Constants.LEARN_RECORDING_ACTIVITY_CLASS_NAME);
        getActivity().startActivity(intent);
    }

    /**
     * 岗位排名点击
     */
    public void postRankingClick() {
        String userId = TypeUtils.getJsonString(currUserJsonObject, "id");
        getHomeActivity().openHtml5Fragment("经验排名", "http://borgwardapp.com/html/ranklist.php?userid=" + userId);
    }

    @UiThread
    @Override
    public void loadHomeDataSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        JSONObject dataJsonObject = TypeUtils.getJsonObject(jsonObject, "data");
        currUserJsonObject = TypeUtils.getJsonObject(dataJsonObject, "user");
        String userId = TypeUtils.getJsonString(currUserJsonObject, "id");
        getBaseActivity().setUserId(userId);
        homeNewsImageAdapter.setFocusJsonArray(TypeUtils.getJsonArray(dataJsonObject, "focus"));
        updateData();
    }

    @UiThread
    @Override
    public void loadHomeDataError(String error) {
        cancelLoadDataProgressDialog();
        alertMessage(error);
    }

    public void updateData() {
        if (currUserJsonObject != null) {
            //加载图片
            userBitmapLoader.displayImage(TypeUtils.getJsonString(currUserJsonObject, "avatar", ""), userAvatarImage);
            //名字
            homeNameText.setText(TypeUtils.getJsonString(currUserJsonObject, "name", ""));
            String city = TypeUtils.getJsonString(currUserJsonObject, "city", "");
            String dealer = TypeUtils.getJsonString(currUserJsonObject, "dealer", "");
            String position = TypeUtils.getJsonString(currUserJsonObject, "position", "");
            StringBuffer explanation = new StringBuffer();

            if (city != null && !"".equals(city) && !"null".equals(city)) {
                explanation.append(city);
                explanation.append(" ");
            }
            if (dealer != null && !"".equals(dealer) && !"null".equals(dealer)) {
                explanation.append(dealer);
//                explanation.append("*");
            }
//            if (position != null && !"".equals(position)) {
//                explanation.append(position);
//            }
            // 主页用户说明--成都*建国宝沃*金牌*销售顾问
            homeExplanation.setText(String.valueOf(explanation));
            String experienceTitle = TypeUtils.getJsonString(currUserJsonObject, "experienceTitle", "");
            //兵等级
            homeGradeTextView.setText(experienceTitle);
            int learningProgress = TypeUtils.getJsonInteger(currUserJsonObject, "learningProgress", 0);
            homeLearningProgressView.setCurrProgress(learningProgress);
            //学习进度
            homeLearningProgressText.setText(learningProgress + "%");
            //经验
            homeExperienceTextView.setText(String.valueOf(TypeUtils.getJsonInteger(currUserJsonObject, "experience", 0)));
            homePosition.setText(position);
            //排名   "experienceNationalRank": 1, 国家排名 "experienceRegionalRank": 1,地区排名    "experienceGgroupRank": 1, 排名
            homeRankingTextView.setText(String.valueOf(TypeUtils.getJsonInteger(currUserJsonObject, "experiencePositionRank", 0)));
//            //品牌大师
//            medalBrandImage.setVisibility(View.GONE);
            medalBrandImage.setAlpha(0x5A);
////            商品大师
//            medalGoodsImage.setVisibility(View.GONE);
            medalGoodsImage.setAlpha(0x5A);
////              形象大师
//            medalImage.setVisibility(View.GONE);
            medalImage.setAlpha(0x5A);
////             维保大师
//            medalRepairImage.setVisibility(View.GONE);
            medalRepairImage.setAlpha(0x5A);
////            	销售大师
//            medalSalesImage.setVisibility(View.GONE);
            medalSalesImage.setAlpha(0x5A);
////            服务大师
//            medalServiceImage.setVisibility(View.GONE);
            medalServiceImage.setAlpha(0x5A);
            JSONArray medals = TypeUtils.getJsonArray(currUserJsonObject, "medals");
            for (int i = 0; i < TypeUtils.getJsonArraySize(medals); i++) {
//                1	形象大师
//                2	维保大师
//                3	服务大师
//                4	销售大师
//                5	商品大师
//                6	品牌大师
                int itemMedal = TypeUtils.getJsonInteger(medals, i);
                if (itemMedal == 1) {
                    medalImage.setAlpha(0xFF);

                } else if (itemMedal == 2) {
                    medalRepairImage.setAlpha(0xFF);
                } else if (itemMedal == 3) {
                    medalServiceImage.setAlpha(0xFF);
                } else if (itemMedal == 4) {
                    medalSalesImage.setAlpha(0xFF);
                } else if (itemMedal == 5) {
                    medalGoodsImage.setAlpha(0xFF);
                } else if (itemMedal == 6) {
                    medalBrandImage.setAlpha(0xFF);
                }
            }


            homeFeatsTextView.setText(String.valueOf(TypeUtils.getJsonArraySize(medals)));
        }
    }

    /**
     * 我的经验头衔
     */
    public void openMyExperienceTitleFragment() {
        getHomeActivity().openMyExperienceTitleFragment(TypeUtils.getJsonInteger(currUserJsonObject, "experience", 0));
    }

    @Override
    public void onDestroyView() {
        isAutomaticScroll = false;
        automaticScroll = null;
        super.onDestroyView();
    }


}
